<?php

declare(strict_types=1);

namespace app\admin\model;

use think\Model;

class LogisticsCompany extends BaseModel
{
    // 定义数据表名
    protected $name = 'logistics_company';

    // 定义主键
    protected $primaryKey = 'id';

    // 定义创建时间字段名
    protected $createTime = 'create_time';

    // 定义更新时间字段名
    protected $updateTime = 'update_time';
    // 定义自动时间戳
    protected $autoWriteTimestamp = true;

    // 设置字段信息
    protected $schema = [
        'id'          => 'int',
        'name'       => 'string',
        'company_type' => 'int',
        'fl_id'      => 'int',
        'status'      => 'int',
        'create_time' => 'datetime',
        'creator'     => 'int',
        'update_time' => 'datetime',
        'updater'     => 'int',
        'is_del'      => 'int',
    ];

    // 定义一个通用的访问器来获取属性值
    protected $attributes = [
        'status' => [
            0 => '关闭',
            1 => '开启'
        ],
        'company_type' => [
            1 => '货代/物流公司',
            2 => '承运/快递公司'
        ]
    ];

    /**
     * 获取父级公司关联
     */
    public function parentCompany()
    {
        return $this->belongsTo(self::class, 'fl_id', 'id')
            ->field('id,name')
            ->bind(['parent_name' => 'name']);
    }

    /**
     * 获取父级公司名称
     */
    public function getParentNameAttr($value, $data)
    {
        return $value ?: '';
    }

    public function getAttr($name)
    {
        // 检查是否是要处理的特殊属性
        if (strpos($name, '_value') !== false) {
            $originalField = str_replace('_value', '', $name);
            if (isset($this->attributes[$originalField])) {
                $value = $this->getData($originalField);
                return $this->attributes[$originalField][$value] ?? '未知';
            }
        }

        // 如果不是特殊属性，调用父类的方法
        return parent::getAttr($name);
    }

    public function getFieldEnum($field)
    {
        if ('ALL' === strtoupper($field)) {
            // 获取所有数据
            $companies = $this->getAllCompanies();

            // 处理数据
            $processedData = $this->processCompanyData($companies);

            return [
                'status' => $this->attributes['status'],
                'company_type' => $this->attributes['company_type'],
                'parent_companies' => $processedData['parent_companies'],
                'child_companies' => $processedData['child_companies'],
                'company_tree' => $processedData['tree']
            ];
        } else {
            return [$field => $this->$field];
        }
    }

    /**
     * 获取所有未删除的公司数据
     * @return array
     */
    public function getAllCompanies()
    {
        return $this->where('is_del', 0)
            ->field('id, name, company_type, fl_id, status')
            ->select()
            ->toArray();
    }

    /**
     * 处理公司数据，分类并构建树形结构
     * @param array $companies
     * @return array
     */
    public function processCompanyData($companies)
    {
        $parentCompanies = [];
        $childCompanies = [];
        $childMap = [];

        // 第一步：分类数据
        foreach ($companies as $company) {
            $childMap[$company['id']] = $this->prepareTreeNode($company);

            if ($this->isValidParentCompany($company)) {
                $parentCompanies[] = $this->extractBasicInfo($company);
            } elseif ($this->isValidChildCompany($company)) {
                $childCompanies[] = $this->extractChildInfo($company);
            }
        }

        // 第二步：构建树形结构
        $tree = $this->buildCompanyTree($companies, $childMap);

        return [
            'parent_companies' => $parentCompanies,
            'child_companies' => $childCompanies,
            'tree' => $tree
        ];
    }

    /**
     * 准备树节点数据
     * @param array $company
     * @return array
     */
    public function prepareTreeNode($company)
    {
        return array_merge($company, ['children' => []]);
    }

    /**
     * 判断是否为有效的父级公司
     * @param array $company
     * @return bool
     */
    public function isValidParentCompany($company)
    {
        return $company['company_type'] == 1 && $company['status'] == 1;
    }

    /**
     * 判断是否为有效的子级公司
     * @param array $company
     * @return bool
     */
    public function isValidChildCompany($company)
    {
        return $company['company_type'] == 2 && $company['status'] == 1;
    }

    /**
     * 提取基本信息
     * @param array $company
     * @return array
     */
    public function extractBasicInfo($company)
    {
        return [
            'id' => $company['id'],
            'name' => $company['name']
        ];
    }

    /**
     * 提取子公司信息
     * @param array $company
     * @return array
     */
    public function extractChildInfo($company)
    {
        return [
            'id' => $company['id'],
            'name' => $company['name'],
            'fl_id' => $company['fl_id']
        ];
    }

    /**
     * 构建公司树形结构
     * @param array $companies
     * @param array $childMap
     * @return array
     */
    public function buildCompanyTree($companies, &$childMap)
    {
        $tree = [];

        foreach ($companies as $company) {
            if ($company['company_type'] == 2 && isset($childMap[$company['fl_id']])) {
                // 添加子公司到父公司的children中
                $childMap[$company['fl_id']]['children'][] = &$childMap[$company['id']];
            } elseif ($company['company_type'] == 1) {
                // 添加父公司到树的根节点
                $tree[] = &$childMap[$company['id']];
            }
        }

        return $tree;
    }

    /**
     * @describe 获取下拉框格式数据
     * @author: Bobo
     * @date: 2024-08-23 10:06:27
     * @param [type] @required
     * @return Renderable
     */
    public function getSelectOption(array $where, $fields = 'id, name')
    {
        $data = $this
            ->field($fields)
            ->where($where)
            ->select()
            ->toArray();

        $selectOption = [];
        foreach ($data as $option) {
            $selectOption[intval($option['id'])] = $option['name'];
        }
        return $selectOption;
    }
}
